#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: login_ui.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 模块详细功能描述
"""
from pathlib import Path
import logging
from typing import Optional

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QFormLayout,
    QGridLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QToolButton,
    QVBoxLayout,
    QWidget,
)

from pathlib import Path
from .common_ui import LogPanel, InfoWithImageDialog, get_project_root
from openpyxl import load_workbook
from function_code.login.login_information import get_user_info
from function_code.login.login_information import account_and_key_verification
from comm.common_code import clear_log


class LoginPage(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self._init_ui()

    def _init_ui(self) -> None:
        root_layout = QVBoxLayout(self)

        # 顶部表单
        form_group = QGroupBox()
        form_layout = QGridLayout(form_group)
        form_layout.setHorizontalSpacing(10)
        form_layout.setVerticalSpacing(10)

        self.input_cookie = QLineEdit()
        self.input_company_id = QLineEdit()
        self.input_project_id = QLineEdit()
        self.input_api_account = QLineEdit()
        self.input_api_key = QLineEdit()
        self.input_access_token = QLineEdit()
        self.input_access_token.setReadOnly(True)

        self.input_api_key.setEchoMode(QLineEdit.Password)

        # 行1 Cookie + 测试Cookie按钮
        form_layout.addWidget(QLabel("*Cookie:"), 0, 0)
        form_layout.addWidget(self.input_cookie, 0, 1)
        form_layout.addWidget(self._help_btn(), 0, 2)

        self.btn_test_cookie = QPushButton("测试Cookie获取公司ID、项目ID")
        self.btn_test_cookie.setFixedHeight(32)
        form_layout.addWidget(self.btn_test_cookie, 0, 3, 1, 2)

        # 行2 公司ID + 项目ID
        form_layout.addWidget(QLabel("*公司ID:"), 1, 0)
        form_layout.addWidget(self.input_company_id, 1, 1)
        form_layout.addWidget(self._help_btn(), 1, 2)

        form_layout.addWidget(QLabel("*项目ID:"), 1, 3)
        form_layout.addWidget(self.input_project_id, 1, 4)
        form_layout.addWidget(self._help_btn(), 1, 5)

        # 行3 API账号 + 密钥
        form_layout.addWidget(QLabel("*API帐号:"), 2, 0)
        form_layout.addWidget(self.input_api_account, 2, 1)
        form_layout.addWidget(self._help_btn(), 2, 2)

        form_layout.addWidget(QLabel("*API密钥:"), 2, 3)
        form_layout.addWidget(self.input_api_key, 2, 4)
        form_layout.addWidget(self._help_btn(), 2, 5)
        
        # 行4 access_token
        form_layout.addWidget(QLabel("access_token:"), 3, 0)
        form_layout.addWidget(self.input_access_token, 3, 1)
        form_layout.addWidget(self._help_btn(), 3, 2)

        # 行5 测试并保存
        self.btn_test_and_save = QPushButton("获取access_token并保存以上信息")
        form_layout.addWidget(self.btn_test_and_save, 4, 0, 1, 2)

        tip_label = QLabel(
            "说明！以上信息您只需要输入Cookie ， Cookie有效期大约在3-6个月左右，3个月后过期再重新获取！\n"
            "access_token有效期2小时，每次启动软件都会自动化获取，过期后点击“获取access_token并保存以上信息”按钮即可。",
        )
        tip_label.setStyleSheet("color:#666;")
        form_layout.addWidget(tip_label, 4, 2, 1, 4)

        root_layout.addWidget(form_group)

        # 日志面板 - 使用login_logger记录器
        self.log_panel = LogPanel()
        root_layout.addWidget(self.log_panel)
        # 附加日志处理器到根日志记录器
        self.log_panel.attach_comm_logger()

        # 事件绑定
        self.btn_test_cookie.clicked.connect(self._on_test_cookie)
        self.btn_test_and_save.clicked.connect(self._on_test_and_save)

        # 默认加载配置
        self._load_default_config()

        # 帮助提示绑定
        self._bind_help_popups(form_layout)

    @staticmethod
    def _help_btn() -> QToolButton:
        btn = QToolButton()
        btn.setText("❓")
        btn.setAutoRaise(True)
        btn.setToolTip("查看填写说明与示例图")
        return btn

    def _bind_help_popups(self, form_layout: QGridLayout) -> None:
        base = get_project_root() / "files" / "software_image_icon"
        items = [
            (0, 2, "Cookie", base / "Cookie.png", "TAPD》F12》刷新页面》网络》任意tapd接口》Headers》Cookie。\n"
             "Cookie有效期大约在3-6个月左右，过期再重新获取。"),
            (1, 2, "公司ID", base / "公司ID.png", "TAPD》公司管理》公司名称下方的ID就是公司ID，或URL中tapd.cn后面的数字。\n"
             "无需输入，点击上方的“测试Cookie获取公司ID、项目ID”按钮会自动获取。"),
            (1, 5, "项目ID", base / "项目ID.png", "TAPD》进入项目空间》URL中tapd.cn后面的数字就是项目ID。\n"
             "无需输入，点击上方的“测试Cookie获取公司ID、项目ID”按钮会自动获取。"),
            (2, 2, "API账号", base / "API账号.png", "TAPD》公司管理》开放集成》API账号管理》API账号的值。"),
            (2, 5, "API密钥", base / "API秘钥.png", "TAPD》公司管理》开放集成》API账号管理》API秘钥的值。"),
            (3, 2, "access_token", base / "access_token.png", "access_token 2小时过期，每隔2小时需要重新点击“获取access_token并保存以上信息”按钮获取。"),
        ]
        for row, col, title, img, text in items:
            # 帮助按钮在 form_layout 的 (row, col)
            widget = form_layout.itemAtPosition(row, col).widget()
            if isinstance(widget, QToolButton):
                # 悬浮直接展示与点击相同的图文内容
                img_url = img.as_uri()
                html_tooltip = f"<b>{title}</b><br/>{text}<br/><img src='{img_url}' width='320'/>"
                widget.setToolTip(html_tooltip)
                # 点击弹窗
                widget.clicked.connect(lambda _=None, t=title, m=text, p=img: InfoWithImageDialog(t, m, p).exec_())

    # 读取默认配置到输入框
    def _load_default_config(self) -> None:
        excel_path = get_project_root() / "files" / "config_file" / "confg.xlsx"
        try:
            # 确保目录存在
            excel_path.parent.mkdir(parents=True, exist_ok=True)
            # 只在文件存在时读取配置
            if excel_path.exists():
                wb = load_workbook(str(excel_path))
                ws = wb.active
                # 读取第二行数据（根据功能构思文档要求）
                self.input_company_id.setText(str(ws.cell(row=2, column=1).value or ""))
                self.input_api_account.setText(str(ws.cell(row=2, column=2).value or ""))
                self.input_api_key.setText(str(ws.cell(row=2, column=3).value or ""))
                self.input_project_id.setText(str(ws.cell(row=2, column=4).value or ""))
                self.input_cookie.setText(str(ws.cell(row=2, column=6).value or ""))
                self.input_access_token.setText(str(ws.cell(row=2, column=7).value or ""))
        except Exception as e:
            logging.error(f"加载配置文件失败: {str(e)}")

    def _on_test_cookie(self) -> None:
        # 根据功能构思文档要求，先清空日志信息（仅清空界面日志，不清空历史日志文件）
        self.log_panel.clear_screen_logs()
        cookie = self.input_cookie.text().strip()
        company_id, project_id, username, message = get_user_info(cookie)
        logging.info(message)
        if company_id and project_id:
            self.input_company_id.setText(company_id)
            self.input_project_id.setText(project_id)
            logging.info(f"成功获取公司ID: {company_id} 和项目ID: {project_id}")
        else:
            logging.error("获取公司ID和项目ID失败")

    def _on_log_signal(self, message: str, level: int) -> None:
        """处理日志信号并显示到日志面板"""
        if level == logging.INFO:
            logging.info(message)
        elif level == logging.ERROR:
            logging.error(message)

    def _on_test_and_save(self) -> None:
        # 根据功能构思文档要求，先清空日志信息（仅清空界面日志，不清空历史日志文件）
        self.log_panel.clear_screen_logs()
        cookie = self.input_cookie.text().strip()
        api_account = self.input_api_account.text().strip()
        api_key = self.input_api_key.text().strip()
        success, message, access_token = account_and_key_verification(api_account, api_key, cookie)
        if success:
            logging.info(message)
            # 更新access_token输入框
            if access_token:
                self.input_access_token.setText(access_token)
        else:
            logging.error(message)
            logging.error("登录信息测试失败")


